package com.pingao.mp.modular.sys.controller;

import com.pingao.mp.modular.sys.service.UserRolesService;
import com.pingao.mp.modular.sys.service.UserService;
import com.pingao.mp.utils.Constant;
import com.pingao.mp.utils.set.MapBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/sys/userRoles")
public class UserRolesController {

    @Autowired
    private UserRolesService userRolesService;
    @Autowired
    private UserService userService;

    @GetMapping(value = "/get")
    public Object userRolesEdit(@RequestParam("userId") Long userId) {
        MapBuilder<String,Object> m = new MapBuilder<>();
        m.put("user",userService.getUserByIdForRoles(userId)).put("roles",userRolesService.listByUserId(userId));
        return m.get();
    }

    @GetMapping(value = "/list")
    public Object list(@RequestParam("userId") Long userId) {
        return userRolesService.listByUserId(userId);
    }

    @PostMapping(value = "/save")
    public Object UserRolesEdit(
            @RequestParam("userId") Long userId,
            @RequestParam(value = "roleIds", required = false) String roleIds
    ) {
        MapBuilder<String, Object> m = new MapBuilder<>();
        try {
            List<Long> rs = new ArrayList<>();
            if (roleIds != null && roleIds.length() > 0) {
                String[] split = roleIds.split(",");
                for (String s : split) {
                    rs.add(Long.parseLong(s));
                }
            }
            userRolesService.saveUserRoles(userId, rs);
            m.put(Constant.ApiStatus, true).put(Constant.ApiMsg, "修改成功");
        } catch (Exception e) {
            m.put(Constant.ApiStatus, false).put(Constant.ApiMsg, e.getMessage());
        }
        return m.get();
    }
}
